var Device = function(opt){
	var root = this;
	this.opt=opt;
	this.socket=null;
	this.isAutoReconnection=true;
	this.connectionWebSocket();				// 连接websocket
	
	window.onbeforeunload = function() {
		// 页面关闭时关闭备备连接
		root.disconnectionWebsocket();
	}
}
/**
 * 设备websocket
 */
Device.prototype.connectionWebSocket=function(){
	var root = this;
	const SENSOR_INFO_TYPE='sensor';   		// 消息类型-传感器消息
	const SENSOR_ALARM_TYPE='sensor_alarm';  // 消息类型-传感器告警
	const DEVICE_INFO_TYPE='device_info';  // 消息类型-设备属性
	const DEVICE_STATE_TYPE='device_state';  // 消息类型-设备状态
	const DEVICE_ONLINE_TYPE='device_online';  // 消息类型-设备上线
	const DEVICE_OFFLINE_TYPE='device_offline';  // 消息类型-设备下线
	const DEVICE_PORT_TYPE='device_port'; // 消息类型-设备端口
	const CLOUD_PUSH_TYPE = "cloud_push";
	const SENSOR_ONLINE_TYPE = "sensor_online";
	const SENSOR_OFFLINE_TYPE = "sensor_offline";
	this.isAutoReconnection=true;
	
	if(typeof(WebSocket) == "undefined") {
        throw new Exception("您的浏览器不支持WebSocket");
    }else{
        var hostname = location.hostname;
        var port = location.port;
        var socketUrl='ws://'+hostname+':'+port+'/websocket/devices/'+this.opt.deviceId;
        this.socket = new WebSocket(socketUrl);
        // 打开事件
        this.socket.onopen = function() {
            console.log("设备管理websocket已打开");
        };
        // 获得消息事件
        this.socket.onmessage = function(msg) {
        	if(!msg.data){
        		return;
        	}
        	var data = JSON.parse(msg.data);
        	switch(data.type){
        	// 传感器信息事件
        	case SENSOR_INFO_TYPE:
        		root.opt.onSensorInfo?root.opt.onSensorInfo(data.data):console.log('未设置onSensorInfo事件！');
        		break;
        	// 传感器告警事件
        	case SENSOR_ALARM_TYPE:
        		root.opt.onSensorAlarm?root.opt.onSensorAlarm(data.data):console.log('未设置onSensorAlarm事件！');
        		break;
        		// 设备信息事件
        	case DEVICE_INFO_TYPE:
        		root.opt.onDeviceInfo?root.opt.onDeviceInfo(data.data):console.log('未设置onDeviceInfo事件！');
        		break;
        	case DEVICE_STATE_TYPE:
        		root.opt.onDeviceState?root.opt.onDeviceState(data.data):console.log('未设置onDeviceState事件！');
        		break;
        		// 设备信息事件
        	case DEVICE_ONLINE_TYPE:
        		root.opt.onDeviceOnline?root.opt.onDeviceOnline(data.data):console.log('未设置onDeviceOnline事件！');
        		break;
        		// 设备信息事件
        	case DEVICE_OFFLINE_TYPE:
        		root.opt.onDeviceOffline?root.opt.onDeviceOffline(data.data):console.log('未设置onDeviceOffline事件！');
        		break;
        	case DEVICE_PORT_TYPE:
        		root.opt.onDevicePort?root.opt.onDevicePort(data.data):console.log('未设置onDevicePort事件！');
        		break;
        	case CLOUD_PUSH_TYPE:
        		root.opt.onCloudPush?root.opt.onCloudPush(data.data):console.log('未设置onCloudPush事件！');
        		break;
        	case SENSOR_ONLINE_TYPE:
        		root.opt.onSensorOnline?root.opt.onSensorOnline(data.data):console.log('未设置onSensorOnline事件！');
        		break;
        	case SENSOR_OFFLINE_TYPE:
        		root.opt.onSensorOffline?root.opt.onSensorOffline(data.data):console.log('未设置onSensorOffline事件！');
        		break;
        	}
        };
        // 关闭事件
        this.socket.onclose = function() {
            console.log("设备管理websocket已关闭");
            if(root.isAutoReconnection){
            	console.log("正在尝试重连。。。");
            	root.connectionWebSocket();
            }
        };
        // 发生了错误事件
        this.socket.onerror = function() {
        	console.log("连接的websocket发生了错误");
        }
    }
}
/**
 * 断开websocket
 */
Device.prototype.disconnectionWebsocket=function(){
	this.isAutoReconnection=false;
	if(this.socket!=null){
		this.socket.close();
		this.socket=null;
	}
}
/**
 * 获取设备所连接的系统端口号
 */
Device.prototype.getPorts=function(successCallback,failCallback){
	$.ajax({
		type : "GET",
		dataType : "json",
		url : 'http://'+ location.host + '/devices/'+this.opt.deviceId+'/ports?t='+new Date().getTime(),
		success : function(data) {
			if (data.code && data.code != 200 && failCallback) {
				failCallback(data);
				return;
			}
			if(successCallback){
				successCallback(data);
			}
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			if(failCallback){
				failCallback(textStatus);
			}
		}
	});
}
/**
 * 设备启动
 */
Device.prototype.open=function(port,interval,successCallback,failCallback){
	$.ajax({
		type : "POST",
		dataType : "json",
		contentType: "application/json; charset=utf-8",
		url : 'http://'+ location.host + '/devices/'+this.opt.deviceId+'/open/',
		data : JSON.stringify({
			SerialPortName:port,
			intervalSecond:interval
		}),
		success : function(data) {
			if (data.code && data.code != 200 && failCallback) {
				failCallback(data);
				return;
			}
			if(successCallback){
				successCallback(data);
			}
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			if(failCallback){
				failCallback(textStatus);
			}
		}
	});
}
/**
 * 设备关闭
 */
Device.prototype.close=function(successCallback,failCallback){
	$.ajax({
		type : "POST",
		dataType : "json",
		contentType: "application/json; charset=utf-8",
		url : 'http://'+ location.host + '/devices/'+this.opt.deviceId+'/close/',
		success : function(data) {
			if (data.code && data.code != 200 && failCallback) {
				failCallback(data);
				return;
			}
			if(successCallback){
				successCallback(data);
			}
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			if(failCallback){
				failCallback(textStatus);
			}
		}
	});
}

/**
 * 获取云端推送状态
 */
Device.prototype.getCloudPushState=function(successCallback,failCallback){
	$.ajax({
		type : "GET",
		dataType : "json",
		contentType: "application/json; charset=utf-8",
		url : 'http://'+ location.host + '/devices/'+this.opt.deviceId+'/cloudpush?t='+new Date().getTime(),
		success : function(data) {
			if (data.code && data.code != 200 && failCallback) {
				failCallback(data);
				return;
			}
			if(successCallback){
				successCallback(data);
			}
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			if(failCallback){
				failCallback(textStatus);
			}
		}
	});
}

Device.prototype.openCloudPush=function(successCallback,failCallback){
	$.ajax({
		type : "POST",
		dataType : "json",
		contentType: "application/json; charset=utf-8",
		url : 'http://'+ location.host + '/devices/'+this.opt.deviceId+'/cloudpush/open',
		success : function(data) {
			if (data.code && data.code != 200 && failCallback) {
				failCallback(data);
				return;
			}
			if(successCallback){
				successCallback(data);
			}
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			if(failCallback){
				failCallback(textStatus);
			}
		}
	});
}

Device.prototype.closeCloudPush=function(successCallback,failCallback){
	$.ajax({
		type : "POST",
		dataType : "json",
		contentType: "application/json; charset=utf-8",
		url : 'http://'+ location.host + '/devices/'+this.opt.deviceId+'/cloudpush/close',
		success : function(data) {
			if (data.code && data.code != 200 && failCallback) {
				failCallback(data);
				return;
			}
			if(successCallback){
				successCallback(data);
			}
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			if(failCallback){
				failCallback(textStatus);
			}
		}
	});
}